﻿using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.GamerServices;
using System;
using System.Windows.Controls;
using Microsoft.Phone.Shell;

namespace TravisCI
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            App.ViewModel.ResetGithubTokenButton = ApplicationBar.MenuItems[3] as ApplicationBarMenuItem;
            App.ViewModel.SetGithubTokenButtonState();
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        public void ApplicationBarRefresh_Click(object sender, EventArgs e)
        {
            App.ViewModel.LoadData();
        }

        public void ApplicationBarAdd_Click(object sender, EventArgs e)
        {
            Guide.BeginShowKeyboardInput(Microsoft.Xna.Framework.PlayerIndex.One,
                "Please enter a project slug",
                "", "travis-ci/travis-ci", (res) =>
                {
                    string result = Guide.EndShowKeyboardInput(res);
                    if (result != null && !result.Equals(""))
                    {
                        if (result.IndexOf('/') > 0)
                            App.ViewModel.AddRepository(result);
                        else
                            Dispatcher.BeginInvoke(() => MessageBox.Show("Not a valid slug: " + result));
                    }
                }, null);
        }

        public void ApplicationBarAddPrivate_Click(object sender, EventArgs e)
        {
            Guide.BeginShowKeyboardInput(Microsoft.Xna.Framework.PlayerIndex.One,
                "Please enter a private project slug on travis-ci.com",
                "", "owner/repo", (res) =>
                {
                    string result = Guide.EndShowKeyboardInput(res);
                    if (result != null && !result.Equals(""))
                    {
                        if (result.IndexOf('/') > 0)
                            App.ViewModel.AddPrivateRepository(result);
                        else
                            Dispatcher.BeginInvoke(() => MessageBox.Show("Not a valid slug: " + result));
                    }
                }, null);
        }

        public void ApplicationBarRemove_Click(object sender, EventArgs e)
        {
            var item = Pivot.SelectedItem;
            if (item != null)
            {
                App.ViewModel.RemoveRepository(((RepositoryViewModel)item).Slug);
            }
        }

        public void ApplicationBarResetToken_Click(object sender, EventArgs e)
        {
            App.ViewModel.ResetGithubToken();
        }

        public void SelectBuild(object sender, EventArgs e)
        {
            var addedItems = ((SelectionChangedEventArgs)e).AddedItems;
            if (addedItems != null && addedItems.Count > 0)
            {
                var item = (BuildViewModel)addedItems[0];
                var url = String.Format("/BuildPage.xaml?slug={0}&id={1}", item.Slug, item.BuildId);
                if (item.AuthToken != null)
                {
                    url += ("&auth_token=" + item.AuthToken);
                }
                NavigationService.Navigate(new Uri(url, UriKind.Relative));
            }
        }

        private void AuthenticationButton_Ok_Click(object sender, RoutedEventArgs e)
        {
            App.ViewModel.AuthenticateClick(Username.Text, Password.Password);
        }

        private void AuthenticationButton_Cancel_Click(object sender, RoutedEventArgs e)
        {
            App.ViewModel.CancelAuthentication();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (App.ViewModel.AuthenticationVisible == Visibility.Visible)
            {
                App.ViewModel.CancelAuthentication();
                e.Cancel = true;
            }
        }

        public void ApplicationBarAbout_Click(object sender, EventArgs e)
        {
            MessageBox.Show("TravisCI: An inofficial Travis-CI.org client\n" +
                            "Copyright 2012 Tim Felgentreff (timfelgentreff@gmail.com)");
        }
    }
}